const { execSync } = require('child_process');
const fs = require('fs');
const crypto = require('crypto');

class MaddyService {
  constructor() {
    this.dbin = this.getDockerContainer();
  }

  // 获取 Maddy 容器 ID
  getDockerContainer() {
    try {
      const containerId = execSync("docker ps -a | grep 'maddy' | awk '{print $1}'").toString().trim();
      if (!containerId) throw new Error('Maddy 容器未找到');
      return `docker exec -i ${containerId}`;
    } catch (error) {
      throw new Error(`获取 Docker 容器失败: ${error.message}`);
    }
  }

  // 获取域名
  getDomain() {
    try {
      return execSync(`${this.dbin} ls /data/dkim_keys | awk -F'_' '{print $1}' | head -n 1`).toString().trim();
    } catch (error) {
      throw new Error(`获取域名失败: ${error.message}`);
    }
  }

  // 生成随机密码
  generatePassword() {
    return crypto.randomBytes(14).toString('base64');
  }

  // 添加用户
  addUser(username) {
    const domain = this.getDomain();
    const email = `${username}@${domain}`;
    const password = this.generatePassword();

    try {
      execSync(`${this.dbin} maddy creds create --password "${password}" "${email}"`, { stdio: 'ignore' });
      execSync(`${this.dbin} maddy imap-accts create "${email}"`, { stdio: 'ignore' });
      return { email, password };
    } catch (error) {
      throw new Error(`添加用户失败: ${error.message}`);
    }
  }

  // 删除用户
  deleteUser(username) {
    const domain = this.getDomain();
    const email = `${username}@${domain}`;

    try {
      execSync(`echo 'y' | ${this.dbin} maddy creds remove "${email}"`, { stdio: 'ignore' });
      return email;
    } catch (error) {
      throw new Error(`删除用户失败: ${error.message}`);
    }
  }

  // 列出用户
  listUsers() {
    try {
      const output = execSync(`${this.dbin} maddy creds list`).toString().trim();
      return output.split('\n').filter(Boolean);
    } catch (error) {
      throw new Error(`列出用户失败: ${error.message}`);
    }
  }
}

module.exports = MaddyService;

